<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" title="调拨" :visible.sync="visible" width="950px"
             :before-close="cancel">
    <el-alert
      title="请先选择调出仓库，再选择配件"
      type="warning"
      style="margin-bottom: 16px"
      show-icon>
    </el-alert>
    <el-form ref="form" :model="form" label-width="auto" :rules="rules">
      <el-form-item label="调出仓库：" prop="source_warehouse_id">
        <WarehouseSelect :astrict="1" v-model="form.source_warehouse_id" :target_warehouse="form.target_warehouse_id"  placeholder="选择仓库"/>
      </el-form-item>
      <el-form-item label="目标仓库：" prop="target_warehouse_id">
        <WarehouseSelect :astrict="0" v-model="form.target_warehouse_id" :source_warehouse="form.source_warehouse_id" placeholder="选择仓库"/>
      </el-form-item>
      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" placeholder="请输入备注" type="textarea" :rows="5"/>
      </el-form-item>
      <editTable :warehouseId="this.form.source_warehouse_id" :table.sync="form.items" ref="editTableRef"></editTable>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import editTable from "./EditTable.vue";
import WarehouseSelect from "@/views/bom/stock/components/WarehouseSelect.vue";

export default {
  props: {
    // 修改回显的数据
    data: Object
  },
  components: {WarehouseSelect, editTable},
  data() {
    return {
      visible: false,
      loading: false,
      // 表单数据
      form: {
        source_warehouse_id: null,
        target_warehouse_id: null,
        description: null,
        items: [],
      },
      rules: {
        source_warehouse_id: [
          {required: true, message: '请选择调出仓库', trigger: 'change'},
        ],
        target_warehouse_id: [
          {required: true, message: '请选择目标仓库', trigger: 'change'},
        ],
      },
    }
  },
  methods: {
    active() {
      this.visible = true;
    },
    cancel() {
      this.$refs.form.resetFields()
      this.visible = false;
    },
    /*提交*/
    save(formName) {
      let flag = false, flag2 = false
      this.$refs[formName].validate((valid) => flag = valid)
      flag2 = this.$refs.editTableRef.validate()
      if (flag && flag2) {
        const form = JSON.parse(JSON.stringify(this.form))
        form.items = form.items.map(({id, quantity}) => ({id, quantity}))
        this.handlePostForm(form)
      }
    },

    async handlePostForm(form) {
      const res = (await this.$http.post('/inventories/allot', form)).data
      res.success ? this.$message.success(res.msg) : this.$message.error(res.msg)
      this.$emit('reload')
      this.cancel()
    },
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
